<!-- 管理学员 -->
<template>
  <div v-loading="loading">
    <div class="config-step">
      <px-button type="primary" :icon="ArrowLeft" class="back-btn" @click="goBack">返回</px-button>
      <div class="step-form">
        <div>
          <div class="table-top">
            <div>
              <span>学员人数：</span>
              <span>合计</span>
              <span>{{ tableData.length }}</span>
              <span>人</span>
            </div>
            <div>
              <px-button @click="handleBatchDelete">删除</px-button>
              <px-button type="primary" @click="handleAddStudent">添加</px-button>
            </div>
          </div>
          <px-table height="calc(100vh - 420px)" :data="tableData" size="small" border class="common-table" @selection-change="step2TableSelect">
            <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
            <px-table-column prop="realName" label="姓名" min-width="120" show-overflow-tooltip />
            <px-table-column prop="empNo" label="工号" min-width="120" show-overflow-tooltip />
            <px-table-column prop="deptName" label="组织" min-width="120" show-overflow-tooltip />
            <px-table-column prop="phone" label="手机号码" min-width="120" show-overflow-tooltip />
            <px-table-column prop="planTime" label="培训计划时间" min-width="120" show-overflow-tooltip />
            <px-table-column prop="createTime" label="添加时间" min-width="120" show-overflow-tooltip />
            <px-table-column label="操作" width="80" fixed="right" align="center">
              <template #default="scope">
                <px-tooltip content="修改计划" placement="top">
                  <px-button link icon="EditPen" type="danger" @click="handleEditPlan(scope)" />
                </px-tooltip>
                <px-tooltip content="删除" placement="top">
                  <px-button link icon="Delete" type="danger" @click="handleDeleteStudent(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
          <div class="step-footer">
            <px-button @click="cancel">取消</px-button>
            <px-button type="primary" @click="toStep3">保存</px-button>
          </div>
          <div v-if="addStudentVisible">
            <AddStudent v-model:visible="addStudentVisible" @add="confirmAddStudent" />
          </div>
          <px-dialog v-model="editPlanVisible" title="修改培训计划时间" width="650">
            <px-form ref="editPlanFormRef" :model="editPlanForm">
              <px-form-item label="培训计划时间" prop="time" label-width="150">
                <px-date-picker
                  v-model="editPlanForm.time"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :disabled-date="disabledDate"
                />
              </px-form-item>
            </px-form>
            <template #footer>
              <span class="dialog-footer">
                <px-button @click="() => (editPlanVisible = false)">取消</px-button>
                <px-button type="primary" @click="saveBtn">确定</px-button>
              </span>
            </template>
          </px-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs } from "vue";
import { editSearchAPI, getExamListAPI, saveTraineeAPI } from "@/api/knowledge/train";
import { getToken } from "@/utils/auth";
import { ArrowLeft } from "@px-ui/icons-vue";
import axios from "axios";
import { PxMessage, PxMessageBox } from "px-ui";
import AddStudent from "./addStudent.vue";
import dayjs from "dayjs";

const props = defineProps({
  handleType: {
    type: String,
    default: "Add"
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["goBack"]);

const disabledDate = time => {
  // 禁用早于今天的日期（不含今天）
  return dayjs(time).isBefore(dayjs(), "day");
};

const state = reactive({
  loading: false,
  baseForm: {
    name: "",
    type: "",
    className: "",
    exam: "",
    pic: [],
    // imgSrc: "",
    intruction: ""
  },
  tableData: [],
  addStudentVisible: false,
  editPlanVisible: false,
  editPlanForm: {
    time: ""
  },
  tableSelectedData: [],
  courseForm: {
    time: null,
    courseId: "",
    courseName: "",
    courseURL: ""
  },
  editData: {}
});
const { loading, tableData, addStudentVisible, editPlanVisible, editPlanForm } = toRefs(state);

onMounted(() => {
  if (props.handleType === "Edit") {
    editSearch();
  }
});

const handleBatchDelete = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的数据");
    return;
  }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const a1 = state.tableData;
      const a2 = state.tableSelectedData;
      state.tableData = a1.filter(row => !a2.includes(row));
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const getPreview = fileData => {
  const nameAry = fileData?.[0]?.name?.split(".") || [];
  const type = nameAry[nameAry?.length - 1] || "";
  const suffix = type?.toLowerCase();
  const params = ["pptx", "ppt"].includes(suffix) ? { docBizId: fileData[0]?.id } : { id: fileData[0]?.id };
  state.loading = true;
  axios({
    method: "post",
    url: ["pptx", "ppt"].includes(suffix) ? "/ifp/dms/api/v1/training/previewPPTx" : "/ifp/dms/api/v1/doc/preview",
    data: params,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    responseType: "arraybuffer"
  }).then(async res => {
    if (["mp4"].includes(suffix)) {
      previewVideo(res.data);
    } else if (["pptx", "ppt", "pdf"].includes(suffix)) {
      previewPPT(res.data);
    }
    state.loading = false;
  });
};

const previewVideo = data => {
  state.courseForm.courseURL = URL.createObjectURL(new Blob([data]));
};

const previewPPT = data => {
  const blob = new Blob([data], {
    type: "application/pdf;chartset=UTF-8"
  });
  state.courseForm.courseURL = URL.createObjectURL(blob);
};

const goBack = () => {
  emits("goBack");
};

const cancel = () => {
  goBack();
};

const toStep3 = () => {
  handleSubmit();
};

const handleAddStudent = () => {
  state.addStudentVisible = true;
};

const confirmAddStudent = data => {
  data?.data?.map(item => {
    if (state.tableData.filter(v => v.empNo === item.empNo).length === 0) {
      let time = data?.time;
      item.planStartTime = time[0];
      item.planEndTime = time[1];
      let startTime = time[0].split(" ")[0] ?? "";
      let endTime = time[1].split(" ")[0] ?? "";
      item.planTime = startTime + "至" + endTime;
      state.tableData.push(item);
    }
  });
  state.addStudentVisible = false;
};

const step2TableSelect = val => {
  state.tableSelectedData = val;
};

const handleEditPlan = val => {
  const row = val?.row;
  let planStartTime = row?.planStartTime ?? "";
  let planEndTime = row?.planEndTime ?? "";
  state.editPlanForm.time = [planStartTime, planEndTime];
  state.editPlanForm.index = val?.$index;
  state.editPlanVisible = true;
};

// 修改培训计划时间保存
const saveBtn = () => {
  let { index, time } = state.editPlanForm;
  let startTime = time[0].split(" ")[0] ?? "";
  let endTime = time[1].split(" ")[0] ?? "";
  state.tableData[index].planStartTime = time[0];
  state.tableData[index].planEndTime = time[1].split(" ")[0] + " 23:59:59";
  state.tableData[index].planTime = startTime + "至" + endTime;
  state.editPlanVisible = false;
};

const handleDeleteStudent = index => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      state.tableData.splice(index, 1);
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const editSearch = async () => {
  try {
    state.loading = true;
    const params = {
      trainId: props.rowData.id
    };
    const res = await editSearchAPI(params);
    state.editData = res;
    const base = res?.trainingBase;
    state.baseForm = {
      name: base?.name ?? "",
      type: base?.type ?? "",
      className: base.department ?? "",
      exam: base.examId ?? "",
      pic: base.cover ?? "",
      // imgSrc: base.cover,
      intruction: base.intro ?? ""
    };
    state.tableData = res?.trainees?.map(v => {
      return {
        realName: v?.name ?? "",
        empNo: v?.workNo ?? "",
        deptName: v?.org ?? "",
        phone: v?.mobile ?? "",
        userId: v?.userId ?? "",
        createTime: v?.createTime ?? "",
        planStartTime: v?.planStartTime ?? "",
        planEndTime: v?.planEndTime ?? "",
        planTime: v?.planStartTime?.split(" ")[0] + "-" + v?.planEndTime?.split(" ")[0]
      };
    });
    state.courseForm = {
      time: Number(res.trainingContent.period) / 60 ?? "",
      courseId: res.trainingContent.docBizId ?? "",
      courseName: res.trainingContent.docBizName ?? ""
    };
    getPreview([{ id: res?.trainingContent?.docBizId, name: res?.trainingContent?.docBizName }]);
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const save = async () => {
  const { name, type, className, exam, intruction } = state.baseForm;
  const pic = state.baseForm.pic[0]?.response ? state.baseForm.pic?.map(item => item.response.data) : state.baseForm.pic;
  const params = {
    trainingBase: {
      id: props.handleType === "Add" ? null : state.editData.trainingBase.id,
      cover: pic,
      name,
      type,
      department: className,
      examId: exam,
      intro: intruction,
      trainingStatus: props.handleType === "Add" ? null : props.rowData.trainingStatus
    },
    trainees: state.tableData.map(item => {
      return {
        // id: props.handleType === "Add" ? null : state.editData.trainees[0].id,
        trainId: props.handleType === "Add" ? null : state.editData.trainees[0]?.trainId,
        name: item.realName,
        workNo: item.empNo,
        org: item.deptName,
        mobile: item.phone,
        userId: item.userId,
        planStartTime: item?.planStartTime ?? "",
        planEndTime: item?.planEndTime ?? ""
      };
    }),
    trainingContent: {
      id: props.handleType === "Add" ? null : state.editData.trainingContent.id,
      trainId: props.handleType === "Add" ? null : state.editData.trainingContent.trainId,
      docBizId: state.courseForm.courseId,
      period: Number(state.courseForm.time) * 60
    }
  };
  try {
    state.loading = true;
    await saveTraineeAPI(params);
    goBack();
    PxMessage.success(`${props.handleType === "Add" ? "新增" : "编辑"}成功`);
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const handleSubmit = async () => {
  try {
    if (!state?.tableData?.length) {
      PxMessage.error("请添加学员");
      return;
    }
    if (state.tableData.length > 0) {
      save();
    }
  } catch (err) {
    PxMessage.error("所需数据不完整，请检查");
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/trainManage/scss/common.scss");

.config-step {
  position: relative;
  width: 100%;

  .back-btn {
    position: absolute;
    left: 0;
  }

  .step-container {
    width: 400px;
    margin: 0 auto;
  }

  .step-form {
    position: relative;
    width: 80%;
    height: calc(100vh - 240px);
    padding: 40px 0 20px;
    margin: 0 auto;
  }

  .step-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

.table-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.preview-content {
  width: 100%;
  height: calc(100vh - 450px);
}

.item-content-wrap {
  .tip {
    font-size: 12px;
    color: rgb(170 170 170);
  }
}
</style>
